package com.example;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName Quickstart
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/5/19 14:32
 * @Version: 1.0
 */
@Component
public class Quickstart {

    @Autowired
    private SecurityManager securityManager;

    @Autowired
    private SimpleService simpleService;

    /**
     * Sets the static instance of SecurityManager. This is NOT needed for web applications.
     */
    @PostConstruct
    private void init() {
        SecurityUtils.setSecurityManager(securityManager);
    }

    public void run() {

        Subject subject = SecurityUtils.getSubject();

        Assert.isTrue(!subject.isAuthenticated());

        UsernamePasswordToken token = new UsernamePasswordToken("joe.coder", "password");
        subject.login(token);

        Assert.isTrue(subject.isAuthenticated());

        subject.checkRole("user");

        Assert.isTrue(!subject.hasRole("admin"));

        subject.checkPermission("read");

        simpleService.readRestrictedCall();

        try {
            simpleService.writeRestrictedCall();
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        subject.logout();
        Assert.isTrue(!subject.isAuthenticated());
    }
}
